package com.uchengwang.ui.cm_ui.me.ui;

import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.uchengwang.R;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.config.RyConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.HttpCallBack;
import com.uchengwang.functions.http.listener.IHttpManager;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.functions.http.manager.HttpManager;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ui.BaseWithTitleActivity;
import com.uchengwang.ui.cm_ui.login.bean.UserBean;
import com.uchengwang.ui.cm_ui.me.adapter.MembersAdapter;
import com.uchengwang.ui.cm_ui.me.presenter.HttpMeManager;
import com.uchengwang.ui.cm_ui.rychat.bean.InviteUserBean;
import com.uchengwang.ui.cm_ui.rychat.manager.RongChatManager;
import com.uchengwang.ui.cm_ui.rychat.manager.RyGroupManager;
import com.uchengwang.ui.utils.DialogUtils;
import com.uchengwang.ui.utils.LoadingUtils;
import com.uchengwang.ui.utils.UCommonUtil;

import java.util.ArrayList;
import java.util.List;

import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.MessageContent;

import static com.uchengwang.ui.UChengApplication.uid;

/**
 * Created by U城网 on 2017/7/11.
 * 我的好友 个人 或者 社团
 */

public class FriendsActivity extends BaseWithTitleActivity{
    private RecyclerView recycleView;
    private PtrClassicFrameLayout mSwipeRefreshLayout;
    private RecyclerAdapterWithHF mAdapter;
    private MembersAdapter adapter;
    private int type;//6推荐给好友 4选择好友建群  5邀请好友加群
    private List<String> members;//群成员列表
    private long groupId, ownId;//群ID 群主ID
    private String groupName = "";
    private MessageContent content;//转发的消息内容

    private int page= 1, totlaPagers;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ustudy_2);

        type = getIntent().getIntExtra(BaseConfig.TYPE, -1);

        groupId = getIntent().getLongExtra(BaseConfig.GROUP_ID, 0);
        ownId = getIntent().getLongExtra(BaseConfig.OWN_ID, 0);
        groupName = getIntent().getStringExtra(BaseConfig.GROUP_NAME);//邀请人加群 把群名称传过来

        content = getIntent().getParcelableExtra(BaseConfig.BEAN);//包含群推荐的信息
        members = getIntent().getStringArrayListExtra(BaseConfig.MEMBERS);

        switch (type){
            case 6:
                setTitle("推荐给好友");
                setRightText("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //给选中的好友 群发消息
                        getChoose(type);
                    }
                });
                break;
            case 4:
                setTitle("选择好友");
                setRightText("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        getChoose(type);
                    }
                });
                break;
            case 5:
                setTitle("邀请好友");
                setRightText("邀请", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        getChoose(type);
                    }
                });
                break;
        }
        initView();

    }

    private void initView(){
        recycleView = (RecyclerView) findViewById(R.id.u_study_recycleView);
        mSwipeRefreshLayout = (PtrClassicFrameLayout) findViewById(R.id.mRefreshLayout);

        initData();
    }

    private void initData(){
        adapter = new MembersAdapter(this, type);
        if (type ==5){
            adapter.setOwnId(ownId);
        }

        if (members != null && members.size() >0){
            adapter.setMembers(members);
        }
        mAdapter = new RecyclerAdapterWithHF(adapter);
        recycleView.setLayoutManager(new LinearLayoutManager(this));
        recycleView.setAdapter(mAdapter);

        mSwipeRefreshLayout.setAutoLoadMoreEnable(true);
        mSwipeRefreshLayout.setLoadMoreEnable(true);

        mSwipeRefreshLayout.postDelayed(new Runnable() {

            @Override
            public void run() {
                mSwipeRefreshLayout.autoRefresh(true);
            }
        }, 150);

        mSwipeRefreshLayout.setPtrHandler(new PtrDefaultHandler() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                page = 1;
                mSwipeRefreshLayout.loadMoreComplete(true);
                initHttpData(true);
            }
        });

        mSwipeRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void loadMore() {
                page++;
                if (page <= totlaPagers){
                    //当前请求页大于总页数，不再请求
                    initHttpData(false);
                } else {
                    mSwipeRefreshLayout.loadMoreComplete(false);
                }
            }
        });
    }

    /**
     * 获取自己好友 和目前自己的角色一样
     * */
    private void initHttpData(final boolean isRefresh){
        HttpMeManager.getPresenter().getFriends(this, uid, page, 10, 3, 0, new HttpMeManager.UsersListener() {
            @Override
            public void result(int status, int count, List<UserBean> list) {
                if (isRefresh){
                    mSwipeRefreshLayout.refreshComplete();
                }else {
                    mSwipeRefreshLayout.loadMoreComplete(true);
                }

                if (status != 0 ){
                    if (status ==1){
                        adapter.getData().clear();
                        adapter.notifyDataSetChanged();
                    }
                    return;
                }
                totlaPagers = count;
                if (list != null && list.size() > 0){
                    if (isRefresh){
                        adapter.setData(list);
                    }else {
                        adapter.getData().addAll(list);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    /**
     * 获取选择的用户
     * */
    private AlertDialog dialog;
    private String[] stringArray;
    private void getChoose(int itemType){
        //给选中的好友 群发消息
        List<UserBean> list = adapter.getData();
        List<UserBean> beanList = new ArrayList<UserBean>();//选择的用户
        for (UserBean b : list){
            if (b.isCheck()){
                beanList.add(b);
            }
        }
        if (beanList == null || beanList.size() <1 ){
            UCommonUtil.getUtil().showToast(FriendsActivity.this, "请选择");
            return;
        }

        if (itemType == 4 || itemType == 5){
            int size = beanList.size();
            stringArray = new String[size];
            for (int i =0; i< size; i++){
                stringArray[i] = String.valueOf(beanList.get(i).getId());
            }
        }
        switch (itemType){
            case 6://推荐给好友
                if (content == null){
                    return;
                }
                //给选中的发信息
                for (int i =0;i<beanList.size(); i++){
                    UserBean userBean = beanList.get(i);
                    RongChatManager.getUtils().senMsg(content, String.valueOf(userBean.getId()), Conversation.ConversationType.PRIVATE);
                }
                break;
            case 4://选择好友创建群
                if (beanList.size() ==1){
                    UserBean b = beanList.get(0);
                    UCommonUtil.getUtil().toChatActiviy(this, b.getId(), Conversation.ConversationType.PRIVATE, b.getNickName());
                    return;
                }

                View view = LayoutInflater.from(this).inflate(R.layout.dialog_create_group, null, false);
                final EditText editText = (EditText) view.findViewById(R.id.dialog_group);
                Button create = (Button) view.findViewById(R.id.dialog_create);
                create.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        groupName = editText.getText().toString();
                        if (TextUtils.isEmpty(groupName)){
                            UCommonUtil.getUtil().showToast(FriendsActivity.this, "请输入群名");
                            return;
                        }
                        DialogUtils.getUtils().cancel();
                        putInfo(groupName, stringArray);

                    }
                });

                dialog = DialogUtils.getUtils().initView(this, view, true, null);
                break;

            case 5://邀请好友加群
                List<InviteUserBean> userBeanList = new ArrayList<>();
                for (UserBean userBean : beanList){
                    //选中邀请的好友
                    InviteUserBean inviteUserBean = new InviteUserBean();
                    inviteUserBean.setGroupId(groupId);
                    inviteUserBean.setGroupName(groupName);
                    inviteUserBean.setInviteMsg("欢迎您加入该群");
                    inviteUserBean.setToUid(userBean.getId());
                    inviteUserBean.setToNickName(userBean.getNickName());
                    inviteUserBean.setToUserAvatar(userBean.getUserAvatar());

                    userBeanList.add(inviteUserBean);
                }

                RyGroupManager.getManager().inviteMember(this, userBeanList, new OnResultListener() {
                    @Override
                    public void onResult(int stutas, String msg, int total, String data) {
                        if (stutas ==0){
                            LoadingUtils.getUtils().hide();

                            GroupInfoActivity.isDeleteMember = true;
                            UCommonUtil.getUtil().showToast(FriendsActivity.this, "邀请成功");
                            FriendsActivity.this.finish();
                        }
                    }
                });
                break;
        }
    }

    /**
     * 建群
     * 好友群人数10个人
     * */
    private void putInfo(final String groupName, final String[] mems){
        if (UCommonUtil.getUtil().isNeedLogin(this, false)){
            return;
        }

        LoadingUtils.getUtils().loading(this);
        IHttpManager.RequestMethod method = null;
        String url = "";

        MapRequest map = new MapRequest();
        map.put(BaseConfig.GROUP_NAME_UCW, groupName);
        map.put(BaseConfig.IS_PUBLIC, false);
        map.put(BaseConfig.USER_LIMIT, 500);
        map.put(BaseConfig.GROUP_DESC, groupName);
        map.put(BaseConfig.GROUP_LOGO, BaseConfig.FriendLogo);
        map.put(BaseConfig.MEMBER_ROLE, UChengApplication.userRole);
        map.put(BaseConfig.IS_NEED_APPLY, true);
        if (UChengApplication.myUniId >0){
            map.put(BaseConfig.UNI_ID, UChengApplication.myUniId);
        }

        map.put(BaseConfig.CREATE_NICK_NAME, UChengApplication.nickName);
        map.put(BaseConfig.CREATE_UID, UCommonUtil.getUtil().getId());

        map.put(BaseConfig.ADMIN_NICK_NAME, UChengApplication.nickName);
        map.put(BaseConfig.ADMIN_UID, UCommonUtil.getUtil().getId());
        if (mems != null && mems.length >0){
            map.put(BaseConfig.USER_IDS, mems);
        }

        method = RyConfig.FriendGroup.method;
        url = RyConfig.FriendGroup.URL;

        HttpManager.newInstance(this).query(method, url, map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                Log.d("jjf", "status="+status+"=msg="+msg);
                LoadingUtils.getUtils().hide();
                UCommonUtil.getUtil().showToast(FriendsActivity.this, "创建失败");
            }


            @Override
            public void onResp(int status, String msg, String data) {
                Log.d("jjf", "status="+status+"=msg="+msg);
                LoadingUtils.getUtils().hide();
                if (status ==0 ){

                    String groupId = data;
                    BaseConfig.changeGroup = true;
                    UCommonUtil.getUtil().toChatActiviy(FriendsActivity.this, groupId, Conversation.ConversationType.GROUP, groupName);
                    FriendsActivity.this.finish();
                    return;
                }
                if (status ==1){
                    UCommonUtil.getUtil().showToast(FriendsActivity.this, "你已经创建过");
                }else {
                    UCommonUtil.getUtil().showToast(FriendsActivity.this, msg);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        List<UserBean> l = adapter.getData();
        l.clear();
        l = null;

    }
}
